package com.frank.loadinglibrary.common.ring;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.*;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * @author SUQI
 * @date 2021/4/28
 * @description 圆环渐变
 **/
public class RingGradientLoading extends BaseRingLoadingComponent implements Component.DrawTask {
    private HiLogLabel label = new HiLogLabel(HiLog.DEBUG, 1, "CircularGradientLoading");
    private Paint mPaint;
    private float mWidth;
    private float mHeight;
    private float mRadius;
    private RectFloat rectF;
    private AnimatorProperty animatorProperty;


    public RingGradientLoading(Context context) {
        this(context, null);
    }

    public RingGradientLoading(Context context, AttrSet attrSet) {
        this(context, attrSet, "");
    }

    public RingGradientLoading(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init();
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        mHeight = getHeight();
        mWidth = getWidth();
        mRadius = Math.min(mHeight, mWidth) / 2;
        Shader shader = new SweepShader(mWidth / 2, mHeight / 2, colors, null);
        mPaint.setShader(shader, Paint.ShaderType.SWEEP_SHADER);
        rectF = new RectFloat(getPaddingLeft() + strokeWidth, mHeight / 2 - mRadius + getPaddingTop() + strokeWidth, mWidth - getPaddingRight() - strokeWidth, mHeight / 2 + mRadius - getPaddingBottom() - strokeWidth);
        canvas.drawArc(rectF, new Arc(startAngle, sweepAngle, false), mPaint);
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setStyle(isFill ? Paint.Style.FILL_STYLE : Paint.Style.STROKE_STYLE);
        addDrawTask(this);
        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                if (autoStart) {
                    startAnimators();
                }
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
            }
        });
    }

    @Override
    public void startAnimators() {
        animatorProperty = createAnimatorProperty();
        animatorProperty
                .rotate(360)
                .setDuration(4000)
                .setLoopedCount(Animator.INFINITE)
                .start();
    }

    @Override
    protected void releaseSource() {

    }

    @Override
    public void stopAnimators() {
        if (animatorProperty != null) {
            animatorProperty.cancel();
            animatorProperty.end();
        }
    }
}
